<template>
  <d2-container>
    <el-row :gutter="5">
      <el-col :span="4">
        <div class="container" style="min-height:1200px;overflow-y:auto;padding:10px" >
          <el-tree :data="data" node-key="keyStr" :props="defaultProps" @node-click="handleNodeClick" v-loading="treeLoading" >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <el-tag type="success" size="mini" v-if="data.version" class="header-tag">{{data.version}}</el-tag>
              <span class="custom-tree-node-data" style="font-size:14px">{{ data.name }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" v-loading="colLoading">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>
              <span v-if="model.name === ''">请选择接口</span>
              <el-tag type="success" v-if="model.status === '1'" class="header-tag">使用中</el-tag>
              <el-tag type="success" v-if="model.method === 'GET'" class="header-tag">GET</el-tag>
              <el-tag type="danger" v-else-if="model.method === 'POST'" class="header-tag">POST</el-tag>
              <el-tag type="danger" v-else-if="model.status !== '1' &&  model.status !== null" class="header-tag">失效</el-tag>
              <el-tag type="info" v-if="model.version && model.version !== ''" class="header-tag">版本：{{model.version}}</el-tag>
              <el-tag type="info" v-if="model.responseContentType !== ''" class="header-tag">返回类型：{{model.responseContentType}}</el-tag>
              <template v-if="!hasBtn('serversProgressUpdate')">
                <el-tag type="info" v-if="model.serversProgress && model.serversProgress === '1'" class="header-tag">
                  服务端：{{model.developersName}} => 字段定义中
                </el-tag>
                <el-tag type="warning" v-if="model.serversProgress && model.serversProgress === '2'" class="header-tag">
                  服务端：{{model.developersName}} => 假数据
                </el-tag>
                <el-tag type="success" v-if="model.serversProgress && model.serversProgress === '3'" class="header-tag">
                  服务端：{{model.developersName}} => 业务逻辑已实现
                </el-tag>
              </template>
              <template v-if="hasBtn('serversProgressUpdate')">
                <el-button type="info" class="button-new-tag header-tag" size="small" v-if="model.serversProgress && model.serversProgress === '1'" @click="serversTagClick()">
                  服务端：{{model.developersName}} => 字段定义中
                </el-button>
                <el-button type="warning" class="button-new-tag header-tag" size="small" v-if="model.serversProgress && model.serversProgress === '2'" @click="serversTagClick()">
                  服务端：{{model.developersName}} => 假数据
                </el-button>
                <el-button type="success" class="button-new-tag header-tag" size="small" v-if="model.serversProgress && model.serversProgress === '3'" @click="serversTagClick()">
                  服务端：{{model.developersName}} => 业务逻辑已实现
                </el-button>
              </template>
              <template v-if="!hasBtn('clientProgressUpdate')">
                <el-tag type="info" v-if="model.clientProgress && model.clientProgress === '1'" class="header-tag">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 尚未对接
                </el-tag>
                <el-tag type="warning" v-if="model.clientProgress && model.clientProgress === '2'" class="header-tag">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 对接讨论中
                </el-tag>
                <el-tag type="success" v-if="model.clientProgress && model.clientProgress === '3'" class="header-tag">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 对接完成
                </el-tag>
              </template>
              <template v-if="hasBtn('clientProgressUpdate')">
                <el-button type="info" class="button-new-tag header-tag" size="small" v-if="model.clientProgress && model.clientProgress === '1'" @click="clientTagClick()">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 尚未对接
                </el-button>
                <el-button type="warning" class="button-new-tag header-tag" size="small" v-if="model.clientProgress && model.clientProgress === '2'" @click="clientTagClick()">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 对接讨论中
                </el-button>
                <el-button type="success" class="button-new-tag header-tag" size="small" v-if="model.clientProgress && model.clientProgress === '3'" @click="clientTagClick()">
                  客户端：{{model.dockingPeopleName ? model.dockingPeopleName : "未知" }} => 对接完成
                </el-button>
              </template>
            </span>
          </div>
          <span v-if="model.name !== ''" style="font-weight: 700">接口名：{{model.name}}</span>
          <p v-if="model.name !== ''">地址：{{model.url}}</p>
          <p v-if="model.name !== ''">Host=>Debug：{{model.host.debug}}</p>
          <p v-if="model.name !== ''">Host=>Online：{{model.host.online}}</p>
        </el-card>
        <el-card class="box-card" style="margin-top:10px" >
          <div slot="header" class="clearfix" >
            <span>请求头</span>
          </div>
          <json-editor ref="responseSuccExam" v-model="model.requestHeader" />
        </el-card>
        <el-card class="box-card" style="margin-top:10px" >
          <div slot="header" class="clearfix" >
            <span style="margin-right:10px">请求参数</span>
            <el-button type="primary" size="mini" @click="handleTest('debug')" :loading="testLoading" >Debug测试</el-button>
            <el-button type="primary" size="mini" @click="handleTest('online')" :loading="testLoading" >Online测试</el-button>
          </div>
          <el-row :gutter="10">
            <el-col :span="12">
              <json-editor ref="responseSuccExam" v-model="model.requestParam" />
            </el-col>
            <el-col :span="12">
              <el-table :data="model.requestParamDesc" border class="table" ref="requestParamDescTable">
                <el-table-column prop="key" label="名称" ></el-table-column>
                <el-table-column prop="isMust" label="必须" width="50" >
                  <p slot-scope="scope" style="margin:0px">
                    {{scope.row.isMust === 'true'?'必须':'可选'}}
                  </p>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="70" ></el-table-column>
                <el-table-column prop="defaultValue" label="默认值" ></el-table-column>
                <el-table-column prop="remark" label="备注" ></el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" style="margin-top:10px" >
          <div slot="header" class="clearfix" >
            <span>返回参数</span>
          </div>
          <el-row :gutter="10">
            <el-col :span="12">
              <json-editor ref="responseSuccExam" v-model="model.responseParam" :readOnly="true" />
            </el-col>
            <el-col :span="12">
              <el-table :data="model.responseParamDesc" border class="table" ref="responseParamDescTable" >
                <el-table-column prop="key" label="名称" ></el-table-column>
                <el-table-column prop="type" label="类型" width="75">
                </el-table-column>
                <el-table-column prop="defaultValue" label="示例">
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" style="margin-top:10px">
          <div slot="header" class="clearfix">
            <span>成功返回示例</span>
          </div>
          <json-editor ref="responseSuccExam" v-model="model.responseSuccExam" :readOnly="true"/>
        </el-card>
        <el-card class="box-card" style="margin-top:10px" >
          <div slot="header" class="clearfix" >
            <span>失败返回示例</span>
          </div>
          <json-editor ref="responseSuccExam" v-model="model.responseErrExam" :readOnly="true" />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :title="updateProgressFrom.title" :visible.sync="updateProgressFrom.show" width="30%">
      <el-form ref="updateProgressFrom" :model="updateProgressFrom.model" :rules="updateProgressFrom.rules" label-width="120px">
        <el-form-item label="用户：" prop="userId">
          <el-select placeholder="请选择用户" v-model="updateProgressFrom.model.userId" class="handle-input mr10">
            <el-option v-for="option in option.userOption" :key='option.id' :value="option.id" :label="option.name" />
          </el-select>
        </el-form-item>  
        <el-form-item label="进度" prop="progress" v-if="updateProgressFrom.model.type == 'servers'">
          <el-select placeholder="请选择进度" v-model="updateProgressFrom.model.progress" class="handle-input mr10">
            <el-option v-for="option in option.serversProgresses" :key='option.value' :value="option.value" :label="option.text" />
          </el-select>
        </el-form-item>  
        <el-form-item label="进度" prop="progress" v-if="updateProgressFrom.model.type == 'client'">
          <el-select placeholder="请选择进度" v-model="updateProgressFrom.model.progress" class="handle-input mr10">
            <el-option v-for="option in option.clientProgresses" :key='option.value' :value="option.value" :label="option.text" />
          </el-select>
        </el-form-item> 
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateProgressFrom.show = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateProgress">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>
<script>
import {
  getInterfaceTree,
  getInfo,
  interfaceTest,
  updateProgress
} from "@/api/interface/interface";
import { userOption } from "@/api/option";
import { isSelected } from '@/utils/validator'
import jsonEditor from "@/components/JsonEditor";
import axios from "axios";
import jwt from "@/utils/jwt/index";
import { connect } from 'net';
import { haveBtn } from '@/utils/colPermissions'; // 列权限
export default {
  components: { jsonEditor },
  data() {
    return {
      data: null,
      model: {
        createTime: "",
        createUser: '',
        description: "",
        id: '',
        method: "",
        moduleId: '',
        name: "",
        useJwt: false,
        serversProgress:'',
        clientProgress:'',
        requestContentType: "",
        requestHeader: null,
        requestOther: null,
        requestParamDesc: [],
        requestParam: null,
        responseContentType: "",
        responseErrExam: null,
        responseParamDesc:[],
        responseParam: null,
        responseSuccExam: null,
        sort: 0,
        status: null,
        url: "",
        version: ""
      },
      updateProgressFrom:{
        title:'',
        show: false,
        rules: {
          userId: [{ validator: isSelected, trigger: 'blur'  }],
          progress: [{ validator: isSelected, trigger: 'blur' }]
        },
        model: {
          id:'',
          userId:'',
          progress:'1',
          type:''
        }
      },
      option:{
        userOption:[],
        serversProgresses:[{text:"字段定义中",value:"1"},{text:"假数据",value:"2"},{text:"业务逻辑已实现",value:"3"}],
        clientProgresses:[{text:"尚未对接",value:"1"},{text:"对接讨论中",value:"2"},{text:"对接完成",value:"3"}]
      },
      treeLoading: false,
      colLoading: false,
      testLoading: false,
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getTreeData();
    this.getUserOption();
  },
  methods: {
    getTreeData() {
      this.treeLoading = true
      getInterfaceTree().then(res => {
        this.data = res.data;
        this.treeLoading = false
      });
    },
    getUserOption() {
      userOption().then(res => {
        this.option.userOption = res.data;
      });
    },
    handleNodeClick(data) {
      if (data.type === "interface") {
        this.colLoading = true
        getInfo({ id: data.id }).then(res => {
          this.model = res.data
          this.colLoading = false
        });
      }
    },
    handleTest(e) {
      this.testLoading = true;
      let url = this.model.url;
      if (this.model.method == "GET" ) {
        url = url + "?" + this.json2Form(this.model.requestParam);
      }
      var param = this.model.requestParam;
      if (this.model.useJwt) {
        param = jwt.jwt(this.model.requestParam);
      } else {
        param = JSON.parse(this.model.requestParam);
      }
      var host = ''
      if(e === 'debug'){
        host = this.model.host.debug
      }
      else{
        host = this.model.host.online
      }
      interfaceTest({
        url: this.model.url,
        method: this.model.method,
        header: JSON.parse(this.model.requestHeader),
        param: param,
        useJwt: this.model.useJwt,
        host: host
      })
        .then(res => {
          this.model.responseParam = JSON.parse(res.data);
          this.testLoading = false;
        })
        .catch(() => {
          this.testLoading = false;
        });
    },
    json2Form(json) {
      var str = [];
      for (var p in json) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
      }
      return str.join("&");
    },
    serversTagClick(){
      this.updateProgressFrom.title = "服务端进度修改"
      this.updateProgressFrom.show = true
      this.updateProgressFrom.model = {
        id : this.model.id,
        type : 'servers',
        userId : this.model.developers,
        progress : this.model.serversProgress
      }
    },
    clientTagClick (){
      this.updateProgressFrom.title = "客户端进度修改"
      this.updateProgressFrom.show = true,
      this.updateProgressFrom.model = {
        id : this.model.id,
        type : 'client',
        userId : this.model.dockingPeople ? this.model.dockingPeople : '',
        progress : this.model.clientProgress
      }
    },
    handleUpdateProgress(){
      this.$refs["updateProgressFrom"].validate((valid) => {
        if (valid) {
          updateProgress(this.updateProgressFrom.model).then(res => {
            if (res.status === 200) {
              this.updateProgressFrom.show = false;
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.colLoading = true
              getInfo({ id: this.updateProgressFrom.model.id }).then(res => {
                this.model = res.data
                this.colLoading = false
              });
            }
            else
            {
              this.$message({ message: res.message, type: 'error' })
            }
          })
        }
        else{
          this.$message({ message: "输入错误", type: 'error' })
          return false;
        }
      })
    },
    hasBtn(e){
      return haveBtn(e)
    }
  }
};
</script>

<style>
.header-tag{
  margin-right: 5px;
}
</style>
